package cn.turboinfo.fuyang.api.domain.admin.usecase.staff;

import cn.turboinfo.fuyang.api.domain.common.service.confidence.ConfidenceCodeService;
import cn.turboinfo.fuyang.api.domain.common.service.staff.HousekeepingStaffService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.domain.util.IdCardUtils;
import cn.turboinfo.fuyang.api.domain.util.PhoneUtils;
import cn.turboinfo.fuyang.api.domain.web.component.file.FileAttachmentHelper;
import cn.turboinfo.fuyang.api.entity.common.fo.staff.HousekeepingStaffImportData;
import cn.turboinfo.fuyang.api.entity.common.fo.staff.HousekeepingStaffImportError;
import cn.turboinfo.fuyang.api.entity.common.pojo.confidence.ConfidenceCode;
import cn.turboinfo.fuyang.api.entity.common.pojo.staff.HousekeepingStaff;
import cn.turboinfo.fuyang.api.entity.common.pojo.staff.HousekeepingStaffCreator;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.helper.component.request.QBeanCreatorHelper;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 导入家政员
 *
 * @author hai
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class HousekeepingStaffImportUseCase extends AbstractUseCase<HousekeepingStaffImportUseCase.InputData, HousekeepingStaffImportUseCase.OutputData> {
    private final HousekeepingStaffService housekeepingStaffService;
    private final FileAttachmentHelper fileAttachmentHelper;
    private final ConfidenceCodeService confidenceCodeService;

    @Override
    protected OutputData doAction(InputData inputData) {

        AtomicInteger successCount = new AtomicInteger();
        AtomicInteger failCount = new AtomicInteger();
        List<HousekeepingStaffImportError> errorList = new ArrayList<>();

        Long fileId = inputData.getFileId();

        File file = fileAttachmentHelper.readFileAttachment(fileId);

        // 处理文件中内容
        EasyExcel.read(file, HousekeepingStaffImportData.class, new PageReadListener<HousekeepingStaffImportData>(dataList -> {

                    for (HousekeepingStaffImportData data : dataList) {
                        data.setCompanyId(inputData.getCompanyId());
                        List<String> errorTextList = new ArrayList<>();
                        Optional<HousekeepingStaff> housekeepingStaffOptional1 = housekeepingStaffService.findByIdCard(data.getIdCard());
                        if (housekeepingStaffOptional1.isPresent()) {
                            errorTextList.add("身份证号已存在");
                        }
                        Optional<HousekeepingStaff> housekeepingStaffOptional2 = housekeepingStaffService.findByMobile(data.getContactMobile());
                        if (housekeepingStaffOptional2.isPresent()) {
                            errorTextList.add("联系电话已存在");
                        }

                        boolean validIdCardNum = IdCardUtils.isValidIdCardNum(data.getIdCard());
                        if (validIdCardNum) {
                            data.setGender(IdCardUtils.judgeGender(data.getIdCard()));
                            data.setProvinceCode(IdCardUtils.getProvinceCode(data.getIdCard()));
                        } else {
                            errorTextList.add("身份证号格式错误");
                        }

                        boolean validPhoneNum = PhoneUtils.isValidPhoneNum(data.getContactMobile());
                        if (!validPhoneNum) {
                            errorTextList.add("联系电话格式错误");
                        }

                        HousekeepingStaffCreator.Builder builder = HousekeepingStaffCreator.builder();
                        QBeanCreatorHelper.copyPropertiesToCreatorBuilder(builder, HousekeepingStaffCreator.class, inputData);

                        // 生成放心码
                        ConfidenceCode confidenceCode = confidenceCodeService.tagging();

                        // TODO: 暂时放弃图片导入
                        // TODO：读取文件

                        // TODO：保存附件

                        // TODO: 保存附件关系

                        if (errorTextList.size() > 0) {
                            failCount.getAndIncrement();

                            errorList.add(HousekeepingStaffImportError.builder()
                                    .name(data.getName())
                                    .displayName(data.getDisplayName())
                                    .idCard(IdCardUtils.maskIdCareNum(data.getIdCard()))
                                    .contactMobile(PhoneUtils.maskPhoneNum(data.getContactMobile()))
                                    .introduction(data.getIntroduction())
                                    .employmentDate(data.getEmploymentDate())
                                    .staffType(data.getStaffType())
                                    .error(String.join(",", errorTextList))
                                    .build());
                        } else {
                            housekeepingStaffService.save(builder
                                    .withCode(confidenceCode.getId().toString())
                                    .build());
                            successCount.getAndIncrement();
                        }


                    }
                }))
                .sheet()
                .headRowNumber(2)
                .doRead();

        return OutputData.builder()
                .successCount(successCount.get())
                .failCount(failCount.get())
                .errorList(errorList)
                .build();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        @NotNull(
                message = "公司编码不能为空"
        )
        private Long companyId;


        @NotNull(
                message = "文件编码不能为空"
        )
        private Long fileId;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
        private Integer successCount;

        private Integer failCount;

        private List<HousekeepingStaffImportError> errorList;
    }

}
